<template>
    <div>
        <el-dialog title="领取礼包" v-dialogDrag :visible.sync="giftDialogVisible" width="480px" :modal-append-to-body="false" :close-on-click-modal="false" @close="resetForm()" center>
            <div class="gift">
                <div style="margin-bottom: 30px">
                    <img class="dengji" :src="dengji" alt="" />
                    <p class="dengji_1">{{ this.user_mes.currentmemLevel === undefined ? 'VIP1' : this.user_mes.currentmemLevel.title }}</p>
                </div>
                <el-form label-position="top" label-width="80px" :model="gameForm" :rules="rules" ref="gameForm" class="gameForm" @submit.native.prevent>
                    <el-form-item label="游戏分区" prop="regional">
                        <el-select v-model="gameForm.regional" placeholder="选择分区" @focus="setMinWidth" :popper-append-to-body="false">
                            <el-option v-for="(item, index) in regional" :key="index" :label="item.title" :value="item.id" :style="{ 'min-width': minWidth + -2 + 'px' }"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="游戏账号" prop="gameAccount">
                        <el-input v-model="gameForm.gameAccount" placeholder="请输入正确的游戏账号"></el-input>
                    </el-form-item>
                </el-form>
                <div class="tishi">
                    <h5>提示</h5>
                    <p v-html="this.exTipText"></p>
                </div>
                <div style="display: flex; text-align: center; margin-top: 30px; margin-bottom: 30px; justify-content: center">
                    <el-button class="button_btn widthHeight" type="primary" size="medium" @click="submitForm_1('gameForm')" :loading="loading">
                        <span v-if="!loading">确定</span>
                        <span v-else>领取中...</span>
                    </el-button>
                    <el-button class="button_close widthHeight" size="medium" @click="resetForm()">取 消</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { getDailyGifts, BagReceivingStatusS, memUserLevels, versionLists, giftTips } from '@/api/url'
export default {
  created () {
    // console.log(this.user_mes.currentmemLevel === undefined)
  },
  data () {
    // 游戏账号验证
    const checkGameAccount = (rule, value, callback) => {
      const sfz = /^[A-Za-z0-9\\d]+$/
      if (!value) {
        return callback(new Error('请输入正确的游戏账号'));
      }
      if (value === '' || sfz.test(value) === false) {
        callback(new Error('请输入正确游戏账号,不支持特殊字符！'))
      } else {
        callback()
      }
    }
    return {
      minWidth: '',
      exTipText: '',// 礼包领取提示
      game_id: '',//游戏id
      startTime: 0, // 初始开始请求时间
      timer: null,
      regional: [], // 分区列表
      loading: false,
      gameForm: {
        regional: '',
        gameAccount: ''
      },
      dengji: '', // 等级图片
      giftDialogVisible: false, // 礼包弹窗
      rules: {
        gameAccount: [
          { trigger: 'blur', validator: checkGameAccount, required: true },
          { min: 2, max: 20, message: '游戏账号在2~20位之间的英文或数字', trigger: 'blur' },
        ],
        regional: [
          { required: true, message: '请选择游戏分区', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
  },
  methods: {
    // 打开领取礼包弹窗
    open_gifsDialog () {
      this.memUserLevels()
      this.giftTipS().then(() => { this.giftDialogVisible = true })
    },
    // 礼包领取提示
    async giftTipS () {
      const res = await giftTips()
      if (res.data.code === 200) {
        this.exTipText = res.data.data
      }
    },
    // 表单重置
    resetForm () {
      this.$refs.gameForm.clearValidate()
      this.gameForm.regional = ''
      this.gameForm.gameAccount = ''
      this.giftDialogVisible = false
    },
    // 获取成长福利数据
    async memUserLevels () {
      try {
        const res = await memUserLevels()
        if (res.data.code === 200) {
          const growth_value_shuju = res.data.data
          growth_value_shuju.forEach(item => {
            if (item.title === this.user_mes.currentmemLevel.title) {
              this.dengji = item.medal
            }
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 根据游戏id获取分区列表
    async versionLists (id) {
      try {
        const res = await versionLists(id)
        this.game_id = id
        // console.log(res)
        if (res.data.code === 200) {
          this.regional = res.data.data
          this.gameName = res.data.gameName
        } else {
          console.log(res.data.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 发送领取礼包请求
    submitForm_1 (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            getDailyGifts({ merGameVersionId: this.game_id, merGamePartitionId: this.gameForm.regional, playerAccount: this.gameForm.gameAccount }).then((res) => {
              if (res.data.code === 200) {
                this.requestId = res.data.requestId
                this.openhandlerData()
              } else {
                this.$message({ message: res.data.msg, type: 'error', center: true })
                this.loading = false
                setTimeout(() => {
                  this.giftDialogVisible = false// 三秒后关闭弹窗
                }, 3000)
              }
            })
          } catch (error) {
            console.log(error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 开始准备轮询
    openhandlerData () {
      this.startTime = new Date().getTime() // 获取触发轮询时的时间
      this.inquireData() // 调用轮询接口,开始进行轮询
    },
    inquireData () {
      const reload = () => {
        clearTimeout(this.timer) // 清除定时器
        // 超过10秒则停止轮询
        if (new Date().getTime() - this.startTime > 10000) {
          clearTimeout(this.timer)
          this.$message({ message: '领取礼包超时!', type: 'error', center: true })
          this.loading = false
          this.giftDialogVisible = false
          return
        }
        // 2s一次, 轮询中
        this.timer = setTimeout(() => {
          this.inquireData() // 调用轮询
        }, 2000)
      }
      BagReceivingStatusS({ requestId: this.requestId })
        .then(res => {
          console.log(res)
          if (res.data.code === 200) {
            // 需要查询的接口返回成功了,做相应的处理
            this.$message({ message: '恭喜你，领取礼包成功!', type: 'success', center: true })
            this.loading = false
            setTimeout(() => {
              this.giftDialogVisible = false// 三秒后关闭弹窗
              clearTimeout(this.timer)
            }, 3000)
          } else {
            if (res.data.lua) {
              this.$message({ message: '脚本错误', type: 'error', center: true })
              // console.log(res.data.msg)
              this.loading = false
              setTimeout(() => {
                this.giftDialogVisible = false// 三秒后关闭弹窗
                clearTimeout(this.timer)
              }, 3000)
              console.log(res.data.lua, 'lua');
            } else if (res.data.error) {
              this.$message({ message: res.data.msg, type: 'error', center: true })
              this.loading = false
              setTimeout(() => {
                this.GameChangeDialogVisible = false// 三秒后关闭弹窗
                clearTimeout(this.timer)
              }, 3000)
              console.log(res.data.error, 'error');
            } else {
              // 没成功,调用轮询
              reload()
            }
          }
        })
        .catch(err => {
          // 请求错误,也继续轮询
          console.log(err)
          reload()
        })
    },
    // 无数据的情况下，给请选择提示设置最小宽度
    setMinWidth (val) {
      let domEmpty = document.getElementsByClassName('el-select-dropdown__empty')
      if (domEmpty.length > 0) {
        domEmpty[0].style['min-width'] = val.srcElement.clientWidth + -2 + 'px'
      }
      this.minWidth = val.srcElement.clientWidth
    },
  },
  computed: { ...mapState(['user_mes', 'user']) },
  watch: {},
  filters: {},
  components: {},
  beforeDestroy () {
    clearTimeout(this.timer)
    this.$EventBus.$off("gift_game_id")
  },
}
</script>

<style scoped lang='less'>
/deep/.el-dialog__header {
    // background: url('@/assets/user/el-dialog__header.png');
    background-size: cover;
    text-align: center;
}
/deep/.el-dialog__body {
    height: 100% !important;
    border-top: 0px;
    padding-bottom: 30px !important;
    background: url('@/assets/dialogImg/VoucherCenterBG.png');
}
.gift {
    .dengji {
        margin-left: 50%;
        transform: translate(-50%, 0);
        height: 90px;
        width: 86px;
    }
    .dengji_1 {
        font-size: 14px;
        font-family: '微软雅黑';
        font-weight: 600;
        text-align: center;
        color: #f1e4c8;
        letter-spacing: 0.56px;
        margin-top: 10px;
    }
    .el-form-item {
        margin-left: 15px;
        margin-right: 15px;
    }
    .el-select {
        width: 100%;
    }
    .tishi {
        margin: 0 15px;
        padding: 10px;
        background: transparent;
        border-radius: 4px;
        h5 {
            font-size: 14px;
            font-family: '微软雅黑';
            font-weight: 400;
            text-align: left;
            color: #dddddd;
            line-height: 20px;
            letter-spacing: 0.12px;
        }
        p {
            font-size: 12px;
            font-family: '微软雅黑';
            font-weight: 400;
            text-align: left;
            color: #ae8d6a;
            line-height: 20px;
            letter-spacing: 0.12px;
        }
    }
    //修改el-input 输入框placeholder颜色
    /deep/input::-webkit-input-placeholder {
        -webkit-text-fill-color: #978152;
    }
}
/deep/.el-select-dropdown__item {
    font-size: 14px;
    padding: 0 20px;
    position: relative;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #606266;
    height: 34px;
    line-height: 34px;
    box-sizing: border-box;
}
/deep/.el-select-dropdown__item.selected {
    font-weight: 400;
}
/deep/.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    display: none;
}
/deep/.el-form-item__label {
    line-height: 15px;
    padding: 0 !important;
    float: left !important;
    font-size: 14px;
    font-family: '微软雅黑';
    color: #f1e4c8;
    letter-spacing: 0.14px;
}
/deep/.el-input__inner {
    color: #ffb331 !important;
}
.widthHeight {
    width: 90px !important;
    height: 38px !important;
}
//修改el-input 输入框placeholder颜色
/deep/input::-webkit-input-placeholder {
    color: #978152;
    font-family: '微软雅黑';
}
</style>
